package com.vf.admin.utils.WYIM;

import com.alibaba.fastjson.JSON;
import com.vf.admin.utils.CheckSumBuilder;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author anxiang
 * @time 2016/3/7.
 */
public class WYMsg {

    private static String APPKEY = "ffd305ffd39b43155689c7ab59dcaf7d";  //AppKey    867021f896ff22658effdca17753dca0
    private static String SECRET = "ddcf40c27ea0";  //AppSecret      a6f687726443

    /**
     * 获取当前时间所在一周的周一和周日时间
     * @return
     */
    public static Map<String,String> getWeekDate() {
        Map<String,String> map = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar cal = Calendar.getInstance();
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if(dayWeek==1){
            dayWeek = 8;
        }

        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        Date mondayDate = cal.getTime();
        String weekBegin = sdf.format(mondayDate);

        cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
        Date sundayDate = cal.getTime();
        String weekEnd = sdf.format(sundayDate);

        map.put("mondayDate", weekBegin);
        map.put("sundayDate", weekEnd);
        return map;
    }

    public 	static String getmin(String time) {
        int h = Integer.parseInt(time) / 60;
        int min = Integer.parseInt(time) % 60;
        String m = null;
        if (min > 10) {
            m = String.valueOf(min);
        } else {
            m = "0" + String.valueOf(min);
        }
        if (Integer.parseInt(time) / 60 > 0) {

            if (h < 10) {
                time = "0" + h + ":" + m;
            } else {
                time = h + ":" + m;
            }
        } else {
            time = "00:" + m;
        }
        return time;
    }

        /**
         * @param str 待转换字符串
         * @return 转换后字符串
         * @throws UnsupportedEncodingException exception
         * @Description 将字符串中的emoji表情转换成可以在utf-8字符集数据库中保存的格式（表情占4个字节，需要utf8mb4字符集）
         */
    public static String emojiConvert1(String str)
            throws UnsupportedEncodingException {
        String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            try {
                matcher.appendReplacement(
                        sb,
                        "[["
                                + URLEncoder.encode(matcher.group(1),
                                "UTF-8") + "]]");
            } catch (UnsupportedEncodingException e) {
                throw e;
            }
        }
        matcher.appendTail(sb);
        System.err.println(str + "------------------------------------" + sb);
        return sb.toString();
    }

    public static List<Date> getWeekDateList() {
        Calendar cal = Calendar.getInstance();
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if(dayWeek==1){
            dayWeek = 8;
        }

        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);
        Date mondayDate = cal.getTime();

        cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
        Date sundayDate = cal.getTime();

        List lDate = new ArrayList();
        lDate.add(mondayDate);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(mondayDate);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(sundayDate);
        //测试此日期是否在指定日期之后
        while (sundayDate.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }

    /**
     * @param str 转换后的字符串
     * @return 转换前的字符串
     * @throws UnsupportedEncodingException exception
     * @Description 还原utf8数据库中保存的含转换后emoji表情的字符串
     */
    public static String emojiRecovery2(String str)
            throws UnsupportedEncodingException {
        String patternString = "\\[\\[(.*?)\\]\\]";

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);

        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            try {
                matcher.appendReplacement(sb,
                        URLDecoder.decode(matcher.group(1), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw e;
            }
        }
        matcher.appendTail(sb);
        System.err.println("emojiRecovery " + str + " to " + sb.toString());
        return sb.toString();
    }

    //推送
    public static String sendAttachMsg(String accid, String msgtype, String to, String attach, String save, String title, String body, Integer sss) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/msg/sendAttachMsg.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("from", accid));
        params.add(new BasicNameValuePair("msgtype", msgtype));
        params.add(new BasicNameValuePair("to", to));
        params.add(new BasicNameValuePair("attach", attach));
        params.add(new BasicNameValuePair("save", save));
        //UTF-8编码,解决中文问题

        String ss = "{\n" +
                "    \"key1\": \"value1\",\n" +
                "    \"apsField\": {\n" +
                "        \"mutable-content\": " + sss + ",\n" +
                "        \"sound\": \"abc.wav\",\n" +
                "        \"alert\": {\n" +
                "            \"title\": \"" + title + "\",\n" +
                "            \"body\": \"" + body + "\"\n" +
                "        },\n" +
                "        \"key2\": \"value2\"\n" +
                "    }\n" +
                "}";
        System.err.println(ss);
        params.add(new BasicNameValuePair("payload", ss));
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //创建网易云通信ID
    public static Map<String, Object> createUser(String accid, String name){
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/user/create.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));
        params.add(new BasicNameValuePair("name", name));
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                JSONObject info = jsonObject.getJSONObject("info");
                String token = (String) info.get("token");
                map.put("code", code);
                map.put("token", token);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //重置网易云通信token
    public static Map<String, Object> refreshToken(String accid) throws IOException {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/user/refreshToken.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                JSONObject info = jsonObject.getJSONObject("info");
                String token = (String) info.get("token");
                map.put("code", code);
                map.put("token", token);
            } else {
                map.put("code", code);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //封禁网易云通信ID
    public static String block(String accid)  {
        String url = "https://api.netease.im/nimserver/user/block.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));
        params.add(new BasicNameValuePair("needkick", "true"));
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //解禁网易云通信ID
    public static String unblock(String accid) {
        String url = "https://api.netease.im/nimserver/user/unblock.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //更新用户名片
    public static Integer updateUinfo(String accid, String name, String icon, String sign, String birth,
                                      String mobile, String gender) {
        String url = "https://api.netease.im/nimserver/user/updateUinfo.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("icon", icon));
        params.add(new BasicNameValuePair("sign", sign));
        params.add(new BasicNameValuePair("mobile", mobile));
        params.add(new BasicNameValuePair("gender", gender));
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            return code;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //获取用户名片
    public static String getUinfos(String accid){
        String url = "https://api.netease.im/nimserver/user/getUinfos.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //账号全局禁言  //账号被设置为全局禁言后，不能发送“点对点”、“群”、“聊天室”消息
    public static Map<String, Object> mute(String accid, String mute){
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/user/mute.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));
        params.add(new BasicNameValuePair("mute", mute));
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                JSONObject info = jsonObject.getJSONObject("info");
                String token = (String) info.get("token");
                map.put("code", code);
                map.put("token", token);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //账号全局禁用音视频
    //设置或取消账号是否可以发起音视频功能；
    //账号被设置为禁用音视频后，不能发起点对点音视频、创建多人音视频、发起点对点白板、创建多人白板
    public static String muteAv(String accid, String mute){
        String url = "https://api.netease.im/nimserver/user/muteAv.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));
        params.add(new BasicNameValuePair("mute", mute));
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //加好友
    public static String addFriend(String accid, String faccid, String type, String msg){
        String url = "https://api.netease.im/nimserver/friend/add.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));//	加好友发起者accid
        params.add(new BasicNameValuePair("faccid", faccid));//  加好友接收者accid
        params.add(new BasicNameValuePair("type", type));//1直接加好友，2请求加好友，3同意加好友，4拒绝加好友
        params.add(new BasicNameValuePair("msg", msg));//加好友对应的请求消息，第三方组装，最长256字符
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //更新好友相关信息   更新好友相关信息，如加备注名，必须是好友才可以
    public static Integer updateFriend(String accid, String faccid, String alias){
        String url = "https://api.netease.im/nimserver/friend/update.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));//	发起者accid
        params.add(new BasicNameValuePair("faccid", faccid));// 要修改朋友的accid
        params.add(new BasicNameValuePair("alias", alias));//给好友增加备注名，限制长度128，可设置为空字符串
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            return code;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //删除好友
    public static String deleteFriend(String accid, String faccid, String isDeleteAlias){
        String url = "https://api.netease.im/nimserver/friend/delete.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));//	发起者accid
        params.add(new BasicNameValuePair("faccid", faccid));// 要修改朋友的accid
        params.add(new BasicNameValuePair("isDeleteAlias", isDeleteAlias));//给好友增加备注名，限制长度128，可设置为空字符串
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //获取好友关系
    public static Map<String, Object> getFriend(String accid, String updatetime){
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/friend/get.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));//发起者accid
        params.add(new BasicNameValuePair("updatetime", updatetime));// 更新时间戳，接口返回该时间戳之后有更新的好友列表
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            List<Map<String, Object>> list = new ArrayList<>();
            if (code == 200) {
                JSONArray friends = jsonObject.getJSONArray("friends");
                if (friends.length() > 0) {
                    for (int i = 0; i < friends.length(); i++) {
                        Map<String, Object> mapp = new HashMap<>();
                        JSONObject job = friends.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                        String faccid = (String) job.get("faccid");
                        mapp.put("faccid", faccid);
                        list.add(mapp);
                    }
                    map.put("data", list);
                    map.put("code", 1);
                } else {
                    map.put("code", 2);
                }
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //设置黑名单/静音
    public static Integer setSpecialRelation(String accid, String targetAcc, String relationType, String value) {
        String url = "https://api.netease.im/nimserver/user/setSpecialRelation.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));//用户帐号，最大长度32字符，必须保证一个APP内唯一
        params.add(new BasicNameValuePair("targetAcc", targetAcc));// 被加黑或加静音的帐号
        params.add(new BasicNameValuePair("relationType", relationType));//本次操作的关系类型,1:黑名单操作，2:静音列表操作
        params.add(new BasicNameValuePair("value", value));//操作值，0:取消黑名单或静音，1:加入黑名单或静音
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            return code;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //查看指定用户的黑名单和静音列表
    public static Map<String, Object> listBlackAndMuteList(String accid) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/user/listBlackAndMuteList.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("accid", accid));//用户帐号，最大长度32字符，必须保证一个APP内唯一
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            List<Map<String, Object>> list = new ArrayList<>();
            if (code == 200) {
                JSONArray blacklist = jsonObject.getJSONArray("blacklist");
                if (blacklist.length() > 0) {
                    for (int i = 0; i < blacklist.length(); i++) {
                        Map<String, Object> mapp = new HashMap<>();
                        String o = (String) blacklist.get(i);
                        mapp.put("blackid", o);
                        list.add(mapp);
                    }
                    map.put("data", list);
                    map.put("code", 1);
                } else {
                    map.put("code", 2);
                }
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //发送普通消息
    public static String sendMsg(String roomid, String fromAccid, String ext, String attach) {

        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(ext);


        String system = (String) jsonObject.get("roomnotice");
        System.err.println(system);

        jsonObject.remove("system");
        jsonObject.remove("roomnotice");


        String s = jsonObject.toJSONString();


        String url = "https://api.netease.im/nimserver/chatroom/sendMsg.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", roomid));//	聊天室id
        String uuid = UUIDUtil.getUUID();
        params.add(new BasicNameValuePair("msgId", uuid));//	客户端消息id，使用uuid等随机串，msgId相同的消息会被客户端去重
        params.add(new BasicNameValuePair("fromAccid", fromAccid));//消息发出者的账号accid
        params.add(new BasicNameValuePair("attach", attach));//消息发出者的账号accid
        params.add(new BasicNameValuePair("msgType", "10"));//自定义消息类型
        params.add(new BasicNameValuePair("ext", ext));//消息扩展字段，内容可自定义，请使用JSON格式，长度限制4096字符
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);

            System.err.println("---------------------------------------"+res);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    //发送广播消息
    public static String broadcastMsg(String body, String isOffline) {
        String url = "https://api.netease.im/nimserver/msg/broadcastMsg.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("body", body));//	聊天室id
        String uuid = UUIDUtil.getUUID();
//        params.add(new BasicNameValuePair("from", "1245860850"));//	客户端消息id，使用uuid等随机串，msgId相同的消息会被客户端去重
        params.add(new BasicNameValuePair("isOffline", isOffline));//消息发出者的账号accid
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res + "444444444444444444444");
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    /**
     * 创建聊天室
     */
    public static Map<String, Object> createRoom(String accid, String name, String announcement, String broadcasturl) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/create.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("creator", accid));
        params.add(new BasicNameValuePair("name", name));//聊天室名称，长度限制128个字符
        params.add(new BasicNameValuePair("announcement", announcement));//公告，长度限制4096个字符
        params.add(new BasicNameValuePair("broadcasturl", broadcasturl));//直播地址
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                JSONObject chatroom = jsonObject.getJSONObject("chatroom");
                Integer roomid = (Integer) chatroom.get("roomid");
                map.put("code", code);
                map.put("roomid", roomid);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    /**
     * 更新聊天室
     */
    public static Map<String, Object> updateRoom(String roomid, String name, String announcement, String broadcasturl)  {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/update.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", roomid));
        params.add(new BasicNameValuePair("name", name));//聊天室名称，长度限制128个字符
        params.add(new BasicNameValuePair("announcement", announcement));//公告，长度限制4096个字符
        params.add(new BasicNameValuePair("queuelevel", "1"));
        params.add(new BasicNameValuePair("broadcasturl", broadcasturl));
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res + "rrrrrrrrrrrrrrrrrrrrrrrrrrrr");
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                map.put("code", code);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    /**
     * 获取聊天室
     */
    public static Map<String, Object> getRoom(String id) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/get.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", id));
        params.add(new BasicNameValuePair("needOnlineUserCount", "true"));//是否需要返回在线人数，true或false，默认false
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                JSONObject chatroom = jsonObject.getJSONObject("chatroom");
                Integer roomid = (Integer) chatroom.get("roomid");
                Boolean muted = (Boolean) chatroom.get("muted");
                String announcement = (String) chatroom.get("announcement");
                String name = (String) chatroom.get("name");
                String broadcasturl = null;
                //JSONObject broad = chatroom.getJSONObject("broadcasturl");
                if (!chatroom.isNull("broadcasturl")) {
                    broadcasturl = (String) chatroom.get("broadcasturl");
                }

                Integer onlineusercount = (Integer) chatroom.get("onlineusercount");
                String ext = (String) chatroom.get("ext");
                String creator = (String) chatroom.get("creator");
                Integer queuelevel = (Integer) chatroom.get("queuelevel");
                Boolean valid = (Boolean) chatroom.get("valid");
                Map<String, Object> mm = new HashMap<>();
                mm.put("muted", muted);
                mm.put("announcement", announcement);
                mm.put("name", name);
                mm.put("valid", valid);
                mm.put("onlineusercount", onlineusercount);
                mm.put("ext", ext);
                mm.put("creator", creator);
                mm.put("broadcasturl", broadcasturl);
                mm.put("queuelevel", queuelevel);
                map.put("code", code);
                map.put("data", mm);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    /**
     * 获取聊天室在线成员信息
     */
    public static String queryMembers(String roomid, String accids)  {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/queryMembers.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", roomid));
        params.add(new BasicNameValuePair("accids", accids));//["abc","def"], 账号列表，最多200条
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res + "-------------------------------");
            JSONObject jsonObject = new JSONObject(res);
            JSONObject desc = jsonObject.getJSONObject("desc");
            JSONArray data = desc.getJSONArray("data");
            if(data.length()<0){
                return "2";
            }
            JSONObject o = data.getJSONObject(0);
            String type = o.getString("type");
            System.err.println(type);
            return type;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    /**
     * 打开或关闭聊天室
     */
    public static Map<String, Object> openRoom(String roomid, String operator, String valid) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/toggleCloseStat.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", roomid));//聊天室id
        params.add(new BasicNameValuePair("operator", operator));//操作者账号，必须是创建者才可以操作
        params.add(new BasicNameValuePair("valid", valid));//true或false，false:关闭聊天室；true:打开聊天室
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                JSONObject info = jsonObject.getJSONObject("desc");
                map.put("code", code);
                map.put("data", info);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    /**
     * 分页获取成员列表
     */
    public static String getRoomUser(String roomid, String type, String endtime, String limit) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/membersByPage.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", roomid));//聊天室id
        params.add(new BasicNameValuePair("type", type));//需要查询的成员类型,0:固定成员;1:非固定成员;2:仅返回在线的固定成员
        params.add(new BasicNameValuePair("endtime", endtime));//单位毫秒，按时间倒序最后一个成员的时间戳,0表示系统当前时间
        params.add(new BasicNameValuePair("limit", limit));//返回条数，<=100
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }


    /**
     * 进入聊天室
     */
    public static Map<String, Object> upRoom(String roomid, String accid) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/requestAddr.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", roomid));//聊天室id
        params.add(new BasicNameValuePair("accid", accid));//进入聊天室的账号
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                map.put("code", code);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }


    /**
     * 将聊天室整体禁言
     */
    public static Map<String, Object> muteRoom(String roomid, String operator, String mute) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/muteRoom.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", roomid));//聊天室id
        params.add(new BasicNameValuePair("operator", operator));//操作者accid，必须是管理员或创建者
        params.add(new BasicNameValuePair("mute", mute));//操作者accid，必须是管理员或创建者
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                map.put("code", code);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }


    /**
     * 将聊天室单个用户禁言
     */
    public static Map<String, Object> temporaryMute(String roomid, String operator, String target, String muteDuration) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/temporaryMute.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", roomid));//聊天室id
        params.add(new BasicNameValuePair("operator", operator));//操作者accid，必须是管理员或创建者
        params.add(new BasicNameValuePair("target", target));//被禁言的目标账号accid
        params.add(new BasicNameValuePair("muteDuration", muteDuration));//0:解除禁言;>0设置禁言的秒数，不能超过2592000秒(30天)
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res + "111111111111111111111111");
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                map.put("code", code);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    /**
     * 设置聊天室内用户角色
     */
    public static Map<String, Object> setMemberRole(String roomid, String operator, String target, String opt, String optvalue) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/setMemberRole.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("roomid", roomid));//聊天室id
        params.add(new BasicNameValuePair("operator", operator));//操作者accid，必须是管理员或创建者
        params.add(new BasicNameValuePair("target", target));//被禁言的目标账号accid
        params.add(new BasicNameValuePair("opt", opt));//0:解除禁言;>0设置禁言的秒数，不能超过2592000秒(30天)
        params.add(new BasicNameValuePair("optvalue", optvalue));//true或false，true:设置；false:取消设置；
        //执行“取消”设置后，若成员非禁言且非黑名单，则变成游客
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            System.err.println(res);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                map.put("code", code);
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }
    /**
     * 单聊云端历史消息查询
     */
    public static String querySessionMsg(String from, String to) {
        String url = "https://api.netease.im/nimserver/history/querySessionMsg.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("from", from));//发送者accid
        params.add(new BasicNameValuePair("to", to));//操作者accid，必须是管理员或创建者
        Date date = new Date();
        Long time = date.getTime();
        Integer i = 24 * 60 * 60 * 1000 * 3;
        Long l = time - i;
        System.err.println(i);
        System.err.println(time);
        params.add(new BasicNameValuePair("begintime", l.toString()));//开始时间，毫秒级
        params.add(new BasicNameValuePair("endtime", time.toString()));//截止时间，毫秒级
        params.add(new BasicNameValuePair("limit", "99"));//true或false，true:设置；false:取消设置；

        //执行“取消”设置后，若成员非禁言且非黑名单，则变成游客
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            return res;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    public static int createChannel(String channelName, String accid)  {
        HashMap<String, Object> map = new HashMap();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://api.netease.im/nimserver/nrtc/createChannel.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("type", "0"));
        params.add(new BasicNameValuePair("channelName", channelName));
        params.add(new BasicNameValuePair("accid", accid));

        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);

            System.out.println(res);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            return code;
        }catch (Exception e){
            System.err.println("失败失败");
            return 100;
        }
    }

    public static Map<String, Object> createHome(String name) {
        HashMap<String, Object> map = new HashMap();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://vcloud.163.com/app/channel/create";
        HttpPost httpPost = new HttpPost(url);

        String nonce = "1";
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(SECRET, nonce, curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", APPKEY);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        // 设置请求的参数
        StringEntity params = new StringEntity("{\"name\":\"" + name + "\", \"type\":0}", Consts.UTF_8);
        httpPost.setEntity(params);
        // 执行请求
        try{
            HttpResponse response = httpClient.execute(httpPost);
            String strResult = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(strResult);
            JSONObject jsonObject = new JSONObject(strResult);
            JSONObject ret = jsonObject.getJSONObject("ret");
            map.put("cid", ret.get("cid"));
            map.put("ctime", ret.get("ctime"));
            map.put("name", ret.get("name"));
            map.put("pushUrl", ret.get("pushUrl"));
            map.put("httpPullUrl", ret.get("httpPullUrl"));
            map.put("hlsPullUrl", ret.get("hlsPullUrl"));
            map.put("rtmpPullUrl", ret.get("rtmpPullUrl"));
            // 打印执行结果
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }

    }
//    public static Result transcodeAddress(@RequestBody Map<String, Object> parMap) throws IOException {
//        HashMap<String, Object> map = new HashMap();
//        DefaultHttpClient httpClient = new DefaultHttpClient();
//        String url = "https://vcloud.163.com/app/transcodeAddress";
//        HttpPost httpPost = new HttpPost(url);
//
//        String nonce = "1";
//        String curTime = String.valueOf((new Date()).getTime() / 1000L);
//        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);//参考 计算CheckSum的java代码
//
//        // 设置请求的header
//        httpPost.addHeader("AppKey", appKey);
//        httpPost.addHeader("Nonce", nonce);
//        httpPost.addHeader("CurTime", curTime);
//        httpPost.addHeader("CheckSum", checkSum);
//        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
//        String cid = (String) parMap.get("cid");
//        // 设置请求的参数
//        StringEntity params = new StringEntity("{\"cid\":\"" + cid + "\"}", Consts.UTF_8);
//        httpPost.setEntity(params);
//
//        // 执行请求
//        HttpResponse response = httpClient.execute(httpPost);
//
//        String strResult= EntityUtils.toString(response.getEntity(), "utf-8");
//        JSONObject jsonObject = new JSONObject(strResult);
//        // 打印执行结果
////        System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
//        Integer code = (Integer) jsonObject.get("code");
//
//        if(code==200) {
//            return sucess("执行成功",map);
//        }
//        return error();
//    }

    public static Map<String, Object> getRoom2(String valueOf) {
        Map<String, Object> map = new HashMap<>();
        String url = "https://api.netease.im/nimserver/chatroom/get.action";
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("roomid",valueOf));
        params.add(new BasicNameValuePair("needOnlineUserCount", "true"));//是否需要返回在线人数，true或false，默认false
        //UTF-8编码,解决中文问题
        try{
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            String res = null;
            try {
                res = NIMPost.postNIMServer(url, entity, APPKEY, SECRET);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.err.println(res);
            JSONObject jsonObject = new JSONObject(res);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 200) {
                JSONObject chatroom = jsonObject.getJSONObject("chatroom");
                Integer roomid = (Integer) chatroom.get("roomid");
                Boolean muted = (Boolean) chatroom.get("muted");
                String announcement = (String) chatroom.get("announcement");
                String name = (String) chatroom.get("name");
                String broadcasturl = "";
                String zhibo = "";
                String cid = "";
                String status = "";
                if (!chatroom.isNull("broadcasturl") && !chatroom.get("broadcasturl").equals("")) {
                    broadcasturl = (String) chatroom.get("broadcasturl");
                    com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(broadcasturl);
                    zhibo = (String) object.get("name");
                    if (!StringUtils.isEmpty(object.get("cid"))) {
                        cid = (String) object.get("cid");
                        System.out.println(cid);
                        Integer s = WYMsg.getRoomStatus(cid);
                        status = String.valueOf(s);
                    }

                }

                Integer onlineusercount = (Integer) chatroom.get("onlineusercount");
                String ext = (String) chatroom.get("ext");
                String creator = (String) chatroom.get("creator");
                Integer queuelevel = (Integer) chatroom.get("queuelevel");
                Boolean valid = (Boolean) chatroom.get("valid");
                Map<String, Object> mm = new HashMap<>();
                mm.put("muted", muted);
                mm.put("announcement", announcement);
                mm.put("name", name);
                mm.put("valid", valid);
                mm.put("onlineusercount", onlineusercount);
                mm.put("broadcasturl", broadcasturl);
                mm.put("ext", ext);
                mm.put("zhibo", zhibo);
                mm.put("creator", creator);
                mm.put("queuelevel", queuelevel);
                mm.put("cid", cid);
                mm.put("zhibostatus", status);
                return mm;
            } else {
                map.put("code", 2);
            }
            return map;
        }catch (Exception e){
            System.err.println("失败失败");
            return null;
        }
    }

    public static Integer getRoomStatus(String valueOf) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://vcloud.163.com/app/channelstats";
        HttpPost httpPost = new HttpPost(url);
        String nonce = "1";
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(SECRET, nonce, curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", APPKEY);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");


        // 设置请求的参数
        StringEntity params = new StringEntity("{\"cid\":\"" + valueOf + "\"}", Consts.UTF_8);
        httpPost.setEntity(params);

        // 执行请求
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);

            String strResult = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject jsonObject = new JSONObject(strResult);
            System.out.println(jsonObject);
            // 打印执行结果
//        System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
            Integer code = (Integer) jsonObject.get("code");
            JSONObject object = (JSONObject) jsonObject.get("ret");

            Integer state = (Integer) object.get("status");
            System.out.println("======----"+state);
            if (code == 200) {
                return state;
            }
        }catch (Exception e){
            return 0;
        }

        return 0;
    }
}
